#include <stdio.h>
#include <string.h>
#include <sqlite3.h>
#include <stdbool.h>
#include <stdlib.h>
#define NULL_LINE (1)


// #define BOOK_1
#ifdef BOOK_1
#define bookname "<老友记>"
#define bookId (1)
#else
#define bookname "<权力的游戏>"
#define bookId (2)
#endif



int handle_slash(char* buf,int len)
{
    char p[1024] = {0};

    for(int i = 0; i < len; i++){
        if(buf[i] == '\"'){
            strcpy(p,&buf[i]);
            buf[i] = '\"';
            strcpy(&buf[i+1],p);
            i+=2;
            len+=1;
        } 
    }

    return 0;
}

//用于每次添加新的阅读材料前获取最大id,当前line.新的阅读材料在此基础上进行累加
// markId:以区分不同的书籍项
//tableBook_name: 不同书籍对应的table名
//line:获取table中的最大line,并返回下一个插入的line应该是多少
//返回值：下一个id
int find_max_id(sqlite3 *db,int markId,char* tableBook_name,int* line)
{
    char *errmsg;
	char sql[1024] = {0};
	char **result;
	int nrow, ncloumn;

    //一个markId代表一本书
	sprintf(sql, "select * from bookmark where markId=%d",markId);
	if(sqlite3_get_table(db, sql, &result, &nrow, &ncloumn, &errmsg) != SQLITE_OK){
		printf("err:%s\n", errmsg);
		return -1;
	}else{
		if(nrow < 1) {
			printf("no markId:%d exist in table 'bookmark'\r\n",markId);
			return -1;
		}

		// printf("nrow:%d ncloumn:%d\n",nrow,ncloumn);
		// int i,k;
		// for (i = 0; i < nrow+1; ++i)//r+1是因为多出来一个列名一行
		// {
		// 	for (k = 0; k < ncloumn; ++k)
		// 	{
		// 		printf("%s result[%d] ", result[i*ncloumn+k],i*ncloumn+k);
		// 	}
		// 	printf("\n");
		// }
        strncpy(tableBook_name,result[7],strlen(result[7]));
		printf("get tableBook_name:%s\r\n",tableBook_name);
	}

	//获取最大id
    memset(sql,0,sizeof(sql));
	sprintf(sql, "SELECT max(id) FROM %s",tableBook_name);
	if(sqlite3_get_table(db, sql, &result, &nrow, &ncloumn, &errmsg) != SQLITE_OK){
		printf("err:%s\n", errmsg);
		return 1;
	}else{
        
        if(result[1] == NULL) {
			printf("find max id in tableBook_name <%s> failed.\r\n",tableBook_name);
			return 1;
		}

        int max_id = atoi(result[1]);

        //找到最大id的词条后提取当前记录到的line,以后新加入进来的词条在当前line上做累加
        sprintf(sql, "select * from %s where id=%d",tableBook_name,max_id);
        if(sqlite3_get_table(db, sql, &result, &nrow, &ncloumn, &errmsg) != SQLITE_OK){
		printf("err:%s\n", errmsg);
		return 1;
        }else{
            if(result[9] == NULL) {
                printf("find max line in tableBook_name <%s> failed.\r\n",tableBook_name);
                return 1;
            }
            *line = atoi(result[9])+2;

            

        }


        //////////////////////////////////////////////

        return max_id+1;
	}

    printf("error, please check.[ %s  : %d]\r\n",__func__,__LINE__);
    exit(0);
}


int ReadingMaterial_extract(sqlite3 *db,char* buf,int len,int* line,bool* isNewChapter,int markId)
{
    static char title[2048] = {0};
    static int id = 1;
    char type[5] = {0};
    char content[2048] = {0};
    char sql[2048] = {0};
    static char tableBook_name[100] = {0};

    //空白行
    if(len <= 2) return NULL_LINE;
    //中英文类型判断
    //做一个中英文标志位翻转逻辑，防止英文中夹杂中文字符在下一步中判断失误
    static bool last_language_type_En = true;
    last_language_type_En = !last_language_type_En;

    bool isChinease = false;
    for(int i = 0; i < len;i++){
        if(buf[i] < 0 && last_language_type_En){
            isChinease = true;
            break;
        }
    }

    //错误保护，防止没有title
    if(0 == strlen(title)) strcpy(title,"NONE");

    //第一次运行默认需要提取id title和line,也就是说，以后每次阅读材料的提取都需要以整个chapter的形式完整放入txt文件中。
    if(*isNewChapter){
        strncpy(title,buf,len);
        id = find_max_id(db,markId,tableBook_name,line);
        *isNewChapter = false;
    }

    // printf("isNewChapter:%s\r\n",*isNewChapter ? "true" : "false");
    

    handle_slash(buf,len);
    sprintf(sql, "insert into %s values(%d, \"%s\", \"%s\", %d, \"%s\", \"%s\")",tableBook_name,id,bookname,title,*line,isChinease ? "Ch" : "En",buf);
    
    printf("%s\r\n",sql);
    

    char *errmsg;
    if( SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg) ){
        printf("err : %s line:%d,id:%d\n", errmsg,*line,id);
        printf("content:%s\n",buf);
        exit(0);
	}

    id += 1;
    return 0;
}

int main(int argc,char* argv[])
{

    //获取写入txt材料名以及是否为新章节
    if(argc < 3){
        printf("usage:%s [txt name] [1/0]   (1-new chapter / 0-content,with no title)\n",argv[0]);
        return 0;
    }

    bool isNewChapter = atoi(argv[2]) == 1 ? true : false;
    // printf("txt name:<%s>\r\nis new chapter: <%s>\r\n",argv[1], isNewChapter ? "true" : "false");

    sqlite3 *db;
    FILE* fp = fopen(argv[1],"r");
    if( NULL == fp ){
		perror("fopen");
		return -1;
	}
    if( SQLITE_OK != sqlite3_open("ReadingMaterial.db", &db) ){
		sqlite3_errmsg(db);
		return -1;
	}

    char buf[2048];
    int line = 1;
    while( fgets(buf, sizeof(buf), fp) != NULL ){
        ReadingMaterial_extract(db,buf,strlen(buf),&line,&isNewChapter,bookId);

        // if(line >= 8) break;
        line++;
        // printf("len:%ld ,",strlen(buf));
        // for(int i = 0; i<strlen(buf);i++){
        //     printf("%d ",buf[i]);
        // }
        // printf("\r\n");
        memset(buf,0,sizeof(buf));
    }

    return 0;
}